<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">三相作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业设定</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >生产工序</text
            >
            <picker
              mode="selector"
              :range="processOptions"
              range-key="text"
              :value="currentProcessIndex"
              @change="handleProcessChange"
              class="form-picker"
              style="flex: 1"
            >
              <view class="picker-content">
                <text>{{
                  currentProcess && currentProcess.processName
                    ? currentProcess.processName
                    : "请选择生产工序"
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: baseline; flex: 1"
          >
            <text class="form-label" style="margin-right: 10px">班别：</text>
            <text class="form-value">{{ workClass || "未设置" }}</text>
          </view>
          <view
            class="form-group"
            style="
              flex-direction: row;
              align-items: baseline;
              flex: 1;
              margin-left: 20px;
            "
          >
            <text class="form-label" style="margin-right: 10px">班次：</text>
            <text class="form-value">{{ workShift || "未设置" }}</text>
          </view>
        </view>
        <view class="form-row" style="overflow: visible;">
          <view class="form-group" style="flex-direction: row; align-items: baseline; flex: 1; overflow: visible;">
            <text class="form-label" style="margin-right: 20rpx">炉次查询日期</text>
            <picker
                mode="date"
                :value="furnaceDate"
                fields="day"
                @change="handleFurnaceDateChange"
                class="form-picker"
                style="flex: 1; z-index: 9999; overflow: visible;"
              >
                <view class="picker-content">
                  <text>{{ furnaceDate }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
          </view>
        </view>
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">炉次设定</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <button class="btn-submit" @tap="handlePrevFurnace">上炉</button>
              <picker
                style="flex: 1"
                mode="selector"
                :range="furnaceOptions"
                range-key="furnaceNo"
                :value="currentFurnaceIndex"
                @change="handleFurnaceChange"
                class="form-picker"
              >
                <view class="picker-content">
                  <text>{{
                    currentFurnace && currentFurnace.furnaceNo
                      ? currentFurnace.furnaceNo
                      : "请选择炉次"
                  }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
              <button class="btn-submit" @tap="handleNextFurnace">下炉</button>
              <button class="btn-submit" @tap="handlePdaPrint">打印</button>
            </view>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">操作备注</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入操作备注"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.operationMemo"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- C. 三相作业表单区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业数据</text>
      </view>

      <!-- 新增10项（从record.vue复制） -->
      <view class="form-section">
        <!-- 冶炼开始和结束按钮放在首行 -->
        <view class="form-row">
          <button
            class="btn-submit"
            :class="{ 'btn-disabled': hasRecordData }"
            :disabled="hasRecordData"
            @click="handleStartSmelting"
            style="flex: 1; margin-right: 8px"
          >
            冶炼开始
          </button>
          <button
            class="btn-submit"
            :class="{ 'btn-disabled': hasRecordData }"
            :disabled="hasRecordData"
            @click="handleEndSmelting"
            style="flex: 1; margin-left: 8px"
          >
            冶炼结束
          </button>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">炉次开始</text>
            <picker
              mode="multiSelector"
              :range="dateTimePickerRange"
              :value="furnaceBeginPickerIndex"
              @change="handleFurnaceBeginChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ formData.furnaceBegin || "请选择炉次开始时间" }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
          <view class="form-group">
            <text class="form-label">炉次结束</text>
            <picker
              mode="multiSelector"
              :range="dateTimePickerRange"
              :value="furnaceEndPickerIndex"
              @change="handleFurnaceEndChange"
              class="form-picker"
            >
              <view class="picker-content">
                <text>{{ formData.furnaceEnd || "请选择炉次结束时间" }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">炉皮重量(KG)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入炉皮重量"
              v-model="formData.furnaceTareWg"
              @blur="validateNumber($event, formData, 'furnaceTareWg')"
            />
          </view>
          <!-- <view class="form-group">
            <text class="form-label">投料重量(KG)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入投料重量"
              v-model.number="formData.furnaceCostWg"
              @blur="validateNumber($event, formData, 'furnaceCostWg')"
            />
          </view> -->
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">出钢重量(KG)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入出钢重量"
              v-model="formData.furnaceOutWg"
              @blur="validateNumber($event, formData, 'furnaceOutWg')"
            />
          </view>
          <view class="form-group">
            <text class="form-label">吹氩时长(分钟)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入吹氩时长"
              v-model.number="formData.arBlowCost"
              @blur="validateNumber($event, formData, 'arBlowCost')"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">合格支数</text>
            <input
              type="number"
              class="form-input"
              placeholder="请输入合格支数"
              v-model.number="formData.qaCount"
              @blur="validateNumber($event, formData, 'qaCount')"
            />
          </view>
          <view class="form-group">
            <text class="form-label">合格重量(KG)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入合格重量"
              v-model="formData.qaWg"
              @blur="validateNumber($event, formData, 'qaWg')"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">废品支数</text>
            <input
              type="number"
              class="form-input"
              placeholder="请输入废品支数"
              v-model.number="formData.scrapCount"
              @blur="validateNumber($event, formData, 'scrapCount')"
            />
          </view>
          <view class="form-group">
            <text class="form-label">废品重量(KG)</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入废品重量"
              v-model="formData.scrapWg"
              @blur="validateNumber($event, formData, 'scrapWg')"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">废品原因</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入废品原因"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.scrapReason"
            />
          </view>
        </view>
      </view>

      <!-- 改号和回炉控件 -->
      <view v-if="hasRecordData" class="form-row" style="margin-bottom: 10px">
        <view
          class="form-group"
          style="
            flex: none;
            width: 100%;
            display: flex;
            align-items: center;
            gap: 10px;
          "
        >
          <view
            style="display: flex; align-items: center"
            @tap.stop="handleReheatClick"
          >
            <view
              class="custom-checkbox-wrapper"
              :class="{ 'checkbox-disabled': isReheatFromDB }"
              style="
                display: flex;
                align-items: center;
                margin-right: 8px;
                padding: 4px;
              "
            >
              <view
                class="custom-checkbox-icon"
                :class="{
                  'checkbox-checked': formData.isReheat,
                  'checkbox-disabled': isReheatFromDB,
                }"
                style="
                  width: 18px;
                  height: 18px;
                  border: 2px solid #ccc;
                  border-radius: 4px;
                  background-color: #fff;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  transition: all 0.3s ease;
                "
              >
                <text
                  v-if="formData.isReheat"
                  style="
                    color: #fff;
                    font-size: 12px;
                    font-weight: bold;
                    line-height: 1;
                  "
                  >✓</text
                >
              </view>
            </view>
            <text
              class="form-label"
              style="margin-bottom: 0; font-size: 14px; padding: 4px"
              :style="{ color: isReheatFromDB ? '#999' : '#333' }"
              >是否回炉</text
            >
          </view>
          <button
            class="btn-modify"
            @click="handleChangeSteelGrade"
            style="
              background: linear-gradient(135deg, #4caf50, #45a049);
              color: #fff;
              height: 32px;
              line-height: 32px;
              padding: 0 16px;
              font-size: 14px;
            "
          >
            改号
          </button>
        </view>
      </view>

      <!-- D. 按钮操作区 -->
      <view class="button-row">
        <button class="btn-reset" @click="handleReset">重置</button>
        <view class="button-group">
          <!-- 暂存按钮：只在未下线时显示（没有记录或状态为暂存） -->
          <button
            v-if="!hasRecordData || currentBusStatus === '暂存'"
            class="btn-submit"
            @click="handleSave"
          >
            暂存
          </button>
          <!-- 修改/下线按钮：如果已下线则显示修改，否则显示下线 -->
          <button
            class="btn-submit"
            @click="
              hasRecordData && currentBusStatus === '下线'
                ? handleUpdate()
                : handleOffline()
            "
          >
            {{ hasRecordData && currentBusStatus === "下线" ? "修改" : "下线" }}
          </button>
        </view>
      </view>
    </view>

    <!-- 改号弹窗 -->
    <view
      v-if="showChangeSteelGradeDialog"
      class="dialog-overlay"
      @tap="
        showChangeSteelGradeDialog = false;
        showSteelGradeDropdown = false;
        steelGradeSearchKeyword = '';
      "
    >
      <view class="dialog-content" @tap.stop.prevent>
        <view class="dialog-header">
          <text class="dialog-title">改号</text>
        </view>
        <view class="dialog-body">
          <view class="dialog-row">
            <text class="dialog-label">当前钢种名称：</text>
            <text class="dialog-value">{{
              currentSteelGradeName || "未设置"
            }}</text>
          </view>
          <view class="dialog-row">
            <text class="dialog-label">修改钢种名称：</text>
            <view class="dialog-picker-wrapper">
              <view
                class="picker-content"
                @tap.stop="showSteelGradeDropdown = !showSteelGradeDropdown"
              >
                <text>{{
                  selectedSteelGrade
                    ? selectedSteelGrade.name
                    : steelGradeOptions.length > 0
                    ? "请选择钢种"
                    : "暂无数据"
                }}</text>
                <text
                  class="picker-arrow"
                  :class="{ 'arrow-up': showSteelGradeDropdown }"
                  >▼</text
                >
              </view>
              <!-- 自定义下拉列表 -->
              <view
                v-if="showSteelGradeDropdown && steelGradeOptions.length > 0"
                class="custom-dropdown"
                @tap.stop
              >
                <!-- 搜索框 -->
                <view class="dropdown-search">
                  <input
                    type="text"
                    class="search-input"
                    placeholder="搜索钢种名称"
                    v-model="steelGradeSearchKeyword"
                    @input="handleSteelGradeSearch"
                    @tap.stop
                  />
                </view>
                <scroll-view
                  scroll-y
                  class="dropdown-scroll"
                  :style="{ maxHeight: '500rpx' }"
                >
                  <view
                    v-for="(item, index) in filteredSteelGradeOptions"
                    :key="index"
                    class="dropdown-item"
                    :class="{
                      'dropdown-item-selected':
                        selectedSteelGrade &&
                        selectedSteelGrade.code === item.code,
                    }"
                    @tap="selectSteelGradeByItem(item)"
                  >
                    <text>{{ item.name }}</text>
                  </view>
                  <view
                    v-if="filteredSteelGradeOptions.length === 0"
                    class="dropdown-empty"
                  >
                    <text>未找到匹配的钢种</text>
                  </view>
                </scroll-view>
              </view>
            </view>
          </view>
        </view>
        <view class="dialog-footer">
          <button
            class="btn-cancel"
            @click="
              showChangeSteelGradeDialog = false;
              showSteelGradeDropdown = false;
              steelGradeSearchKeyword = '';
            "
          >
            取消
          </button>
          <button class="btn-confirm" @click="handleConfirmChangeSteelGrade">
            确认
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { getProcessOptions } from "@/api/md/process";
import { SxBatchApi } from "@/api/pp/sxbatch";
import { SxRecordApi } from "@/api/lz/sxrecord";
import { SteelGradeApi } from "@/api/qm/steelgrade";

// 导入PDA扫码功能
import { pdaScanApi } from "@/pages/smart/pdaScan";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "StockIn",
  // 混入PDA扫码和打印功能
  mixins: [pdaScanApi],
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
        // 新增表单字段
        furnaceNo: "", // 炉次号
        operationMemo: "", // 操作备注
        furnaceBegin: "", // 炉次开始
        furnaceEnd: "", // 炉次结束
        furnaceTareWg: "", // 炉皮重量
        // furnaceCostWg: "", // 投料重量
        furnaceOutWg: "", // 出钢重量
        arBlowCost: "", // 吹氩时长
        qaCount: "", // 合格支数
        qaWg: "", // 合格重量
        scrapCount: "", // 废品支数
        scrapWg: "", // 废品重量
        scrapReason: "", // 废品原因
        isReheat: false, // 是否回炉
      },
      // 是否回炉是否来自数据库（已提交的记录）
      isReheatFromDB: false, // 如果为true，表示是从数据库加载的"是"状态，不允许编辑
      // 炉次查询日期
      furnaceDate: dateHelperApi.getCurrentDate(), // 默认为当天日期
      // 炉次号列表
      furnaceNoList: [],
      // 当前炉次索引
      currentFurnaceIndex: 0,

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组

      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,

      // 是否有已有记录数据
      hasRecordData: false,
      // 当前记录的ID（用于更新）
      currentRecordId: null,
      // 当前记录的编号（用于改号）
      currentRecordNo: null,
      // 当前钢种名称（用于改号）
      currentSteelGradeName: "",
      // 当前记录的业务状态（用于判断是否显示暂存按钮）
      currentBusStatus: null,

      // 改号弹窗相关
      showChangeSteelGradeDialog: false,
      showSteelGradeDropdown: false, // 是否显示下拉列表
      steelGradeSearchKeyword: "", // 钢种搜索关键词
      steelGradeOptions: [], // 钢种选项列表（完整列表）
      selectedSteelGradeIndex: -1,
      selectedSteelGrade: null, // 选中的钢种对象 {code, name, label}

      // 日期时间选择器的索引值 [年索引, 月索引, 日索引, 时索引, 分索引, 秒索引]
      furnaceBeginPickerIndex: [0, 0, 0, 0, 0, 0],
      furnaceEndPickerIndex: [0, 0, 0, 0, 0, 0],
    };
  },
  computed: {
    // 过滤后的钢种选项列表（根据搜索关键词）
    filteredSteelGradeOptions() {
      if (
        !this.steelGradeSearchKeyword ||
        this.steelGradeSearchKeyword.trim() === ""
      ) {
        return this.steelGradeOptions;
      }
      const keyword = this.steelGradeSearchKeyword.trim().toLowerCase();
      return this.steelGradeOptions.filter((item) => {
        return item.name && item.name.toLowerCase().includes(keyword);
      });
    },

    // 日期时间选择器的选项范围
    dateTimePickerRange() {
      const currentYear = new Date().getFullYear();
      const years = [];
      const months = [];
      const days = [];
      const hours = [];
      const minutes = [];
      const seconds = [];

      // 年份：当前年份前后各10年
      for (let i = currentYear - 10; i <= currentYear + 10; i++) {
        years.push(String(i));
      }

      // 月份：1-12
      for (let i = 1; i <= 12; i++) {
        months.push(String(i).padStart(2, "0"));
      }

      // 日期：1-31（实际使用时需要根据年月动态计算）
      for (let i = 1; i <= 31; i++) {
        days.push(String(i).padStart(2, "0"));
      }

      // 小时：0-23
      for (let i = 0; i < 24; i++) {
        hours.push(String(i).padStart(2, "0"));
      }

      // 分钟：0-59
      for (let i = 0; i < 60; i++) {
        minutes.push(String(i).padStart(2, "0"));
      }

      // 秒：0-59
      for (let i = 0; i < 60; i++) {
        seconds.push(String(i).padStart(2, "0"));
      }

      return [years, months, days, hours, minutes, seconds];
    },
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 当前炉次信息
    currentFurnace() {
      if (
        this.furnaceNoList &&
        this.furnaceNoList.length > 0 &&
        this.currentFurnaceIndex >= 0
      ) {
        return {
          furnaceNo: this.furnaceNoList[this.currentFurnaceIndex],
        };
      }
      return null;
    },
    // 炉次选项列表（用于picker组件）
    furnaceOptions() {
      if (this.furnaceNoList && this.furnaceNoList.length > 0) {
        return this.furnaceNoList.map((furnaceNo) => ({
          furnaceNo: furnaceNo,
        }));
      }
      return [];
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 等待工序加载完成后再加载炉次号列表（因为需要工序信息）
    await this.$nextTick();
    await this.loadFurnaceNoList(); // 加载炉次号列表
    // 初始化PDA打印模块（来自mixin）
    this.initScanModule();
  },
  beforeDestroy() {
    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
  methods: {
    /* 加载当前工序 */
    loadCurrentProcess() {
      // 优先强制默认选择“三相”
      if (this.processOptions && this.processOptions.length > 0) {
        // 先精确匹配文本为“三相”，找不到则尝试包含“三相”
        let sxIndex = this.processOptions.findIndex(
          (item) => item.text === "三相"
        );
        if (sxIndex === -1) {
          sxIndex = this.processOptions.findIndex(
            (item) =>
              (item.text && item.text.includes("三相")) ||
              (item.value && String(item.value).includes("SX"))
          );
        }
        if (sxIndex !== -1) {
          this.currentProcess = {
            processCode: this.processOptions[sxIndex].value,
            processName: this.processOptions[sxIndex].text,
          };
          this.formData.processCode = this.currentProcess.processCode;
          this.formData.processName = this.currentProcess.processName;
          this.currentProcessIndex = sxIndex;
          // 同步加载班次班组（若用户配置存在）
          const userData = this.$store.state.user;
          const userConfig =
            userData && userData.userConfig ? userData.userConfig : {};
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";
          return;
        }
      }

      // 若没有找到“三相”，再尝试使用用户缓存
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (
        userData &&
        userData.userConfig &&
        userConfig.processNo &&
        userConfig.processName
      ) {
        this.currentProcess = {
          processCode: userConfig.processNo,
          processName: userConfig.processName,
        };
        this.formData.processCode = userConfig.processNo;
        this.formData.processName = userConfig.processName;

        // 加载班次班组信息
        this.workShift = userConfig.workShift || "";
        this.workClass = userConfig.workClass || "";

        // 在工序选项中找到对应的索引
        const processIndex = this.processOptions.findIndex(
          (item) => item.value === userConfig.processNo
        );
        if (processIndex !== -1) {
          this.currentProcessIndex = processIndex;
        }
        return;
      }

      // 如果没有缓存或缓存无效，默认优先选择“三相”，若不存在则选择第一个工序
      if (this.processOptions.length > 0) {
        const sxIndex = this.processOptions.findIndex(
          (item) => item.text === "三相"
        );
        const targetIndex = sxIndex !== -1 ? sxIndex : 0;
        this.currentProcess = {
          processCode: this.processOptions[targetIndex].value,
          processName: this.processOptions[targetIndex].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = targetIndex;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    async handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;

        // 工序变化后，重新加载炉次号列表
        await this.loadFurnaceNoList();
      }
    },

    // 打印功能（参照pdaPrint.vue）
    async handlePdaPrint() {
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      try {
        // 1) 准备炉号
        const furnaceNo = this.formData.furnaceNo || "";

        // 2) 获取钢种：若前端暂无，调用后端通过炉号查询配料计划，取 steelGrade
        let steelGrade = this.formData.steelGrade || "";
        if (!steelGrade) {
          try {
            const resp = await SxBatchApi.getSxBatchListByRecordNo(furnaceNo);
            // 接口返回 CommonResult<List<...>>，实际数组在 resp.data
            const list = resp?.data || [];
            if (Array.isArray(list) && list.length > 0) {
              steelGrade = list[0].steelGrade || "";
            }
          } catch (e) {
            // 忽略异常，保持为空字符串
          }
        }

        // 3) 当前时间（yyyy-MM-dd）
        const now = new Date();
        const pad = (n) => String(n).padStart(2, "0");
        const nowStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(
          now.getDate()
        )}`;

        console.log(
          "打印参数：炉号、钢种、当前时间",
          furnaceNo,
          steelGrade || "",
          nowStr,
          ""
        );
        // 打印参数：炉号、钢种、当前时间
        const printResult = this.pdaPrint(
          furnaceNo,
          steelGrade || "",
          nowStr,
          ""
        );

        if (printResult) {
          uni.showToast({
            title: "打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("打印失败:", error);
        uni.showToast({
          title: "打印失败，请重试",
          icon: "none",
        });
      }
    },

    /* 炉次号相关方法 */
    // 查询炉次号列表（从配料计划中获取指定日期的第一炉）
    async loadFurnaceNoList() {
      try {
        // 获取当天日期范围
        const today = this.furnaceDate;
        const startTime = `${today} 00:00:00`;
        const endTime = `${today} 23:59:59`;

        // 构建查询参数
        const params = {
          pageNo: 1,
          pageSize: 100, // 获取足够多的数据以确保能找到第一炉
          processName: this.currentProcess.processName || "",
          createTime: [startTime, endTime],
        };

        const response = await SxBatchApi.getSxBatchPage(params);
        console.log("配料计划响应:", response);

        if (response.code === 0 && response.data && response.data.list) {
          // 从配料计划中提取炉次号（recordNo字段），并按升序排序
          const recordNoList = response.data.list
            // 仅保留业务状态为“已下发”的炉次
            .filter((item) => item && item.busStatus === "已下发")
            .map((item) => item.recordNo)
            .filter((recordNo) => recordNo) // 过滤空值
            .sort((a, b) => String(a).localeCompare(String(b))); // 升序：小→大

          this.furnaceNoList = recordNoList;

          // 设置默认选择第一个炉次号（当天的第一炉）
          if (this.furnaceNoList.length > 0) {
            this.formData.furnaceNo = this.furnaceNoList[0];
            this.currentFurnaceIndex = 0;
            console.log("默认选择第一炉:", this.furnaceNoList[0]);
            // 检查该炉次是否有已有数据
            await this.checkAndLoadRecordData(this.furnaceNoList[0]);
          } else {
            uni.showToast({
              title: "当天没有配料计划数据",
              icon: "none",
            });
          }
        } else {
          this.furnaceNoList = [];
          uni.showToast({
            title: response.message || "加载配料计划失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载炉次号列表失败:", error);
        this.furnaceNoList = [];
        uni.showToast({
          title: "加载炉次号失败",
          icon: "none",
        });
      }
    },

    // 上一炉次
    async handlePrevFurnace() {
      if (this.currentFurnaceIndex > 0) {
        this.currentFurnaceIndex--;
        this.formData.furnaceNo = this.furnaceNoList[this.currentFurnaceIndex];
        // 检查该炉次是否有已有数据
        await this.checkAndLoadRecordData(
          this.furnaceNoList[this.currentFurnaceIndex]
        );
      } else {
        uni.showToast({
          title: "已经是第一炉了",
          icon: "none",
        });
      }
    },

    // 下一炉次
    async handleNextFurnace() {
      if (this.currentFurnaceIndex < this.furnaceNoList.length - 1) {
        this.currentFurnaceIndex++;
        this.formData.furnaceNo = this.furnaceNoList[this.currentFurnaceIndex];
        // 检查该炉次是否有已有数据
        await this.checkAndLoadRecordData(
          this.furnaceNoList[this.currentFurnaceIndex]
        );
      } else {
        uni.showToast({
          title: "没有该炉次号，请更换创建日期或提示配料人员进行计划编制",
          icon: "none",
          duration: 3000,
        });
      }
    },

    // 炉次号选择变化
    async handleFurnaceChange(e) {
      const index = e.detail.value;
      this.currentFurnaceIndex = index;
      this.formData.furnaceNo = this.furnaceNoList[index];
      // 检查该炉次是否有已有数据
      await this.checkAndLoadRecordData(this.furnaceNoList[index]);
    },

    // 炉次查询日期变化
    async handleFurnaceDateChange(e) {
      const date = e.detail.value;
      this.furnaceDate = date;
      // 重新加载炉次列表
      await this.loadFurnaceNoList();
    },

    // 检查并加载已有记录数据
    async checkAndLoadRecordData(furnaceNo) {
      if (!furnaceNo) {
        this.hasRecordData = false;
        return;
      }

      try {
        // 使用分页查询接口，通过furnaceNo查询
        const params = {
          pageNo: 1,
          pageSize: 1,
          furnaceNo: furnaceNo,
        };

        const response = await SxRecordApi.getSxRecordPage(params);
        console.log("查询已有记录响应:", response);

        if (
          response.code === 0 &&
          response.data &&
          response.data.list &&
          response.data.list.length > 0
        ) {
          // 有数据，填充表单
          const recordData = response.data.list[0];
          console.log("查询到的记录数据:", recordData);
          console.log("reserveVarchar1字段值:", recordData.reserveVarchar1);
          this.fillFormData(recordData);
          this.hasRecordData = true;
          this.currentRecordId = recordData.id; // 保存记录ID用于更新
          this.currentRecordNo = recordData.recordNo; // 保存记录编号用于改号
          this.currentSteelGradeName = recordData.steelGradeName || ""; // 保存当前钢种名称
          this.currentBusStatus = recordData.busStatus || null; // 保存当前业务状态
          console.log("已加载已有记录数据:", recordData);
          console.log("isReheat状态:", this.formData.isReheat);
          console.log("业务状态:", this.currentBusStatus);
        } else {
          // 没有数据，重置表单
          this.resetFormDataExceptFurnace();
          this.hasRecordData = false;
          this.currentRecordId = null; // 清空记录ID
          this.currentRecordNo = null; // 清空记录编号
          this.currentSteelGradeName = ""; // 清空当前钢种名称
          this.currentBusStatus = null; // 清空业务状态
        }
      } catch (error) {
        console.error("检查已有记录失败:", error);
        // 出错时默认认为没有数据
        this.resetFormDataExceptFurnace();
        this.hasRecordData = false;
        this.currentRecordId = null; // 清空记录ID
        this.currentBusStatus = null; // 清空业务状态
      }
    },

    // 填充表单数据
    fillFormData(recordData) {
      // 基本信息
      this.formData.processCode = recordData.processNo || "";
      this.formData.processName = recordData.processName || "";
      this.formData.operationMemo = recordData.recordMemo || "";

      // 时间信息
      if (recordData.furnaceBegin) {
        // 将后端返回的时间格式转换为前端显示格式
        const beginTime = new Date(recordData.furnaceBegin);
        const year = beginTime.getFullYear();
        const month = String(beginTime.getMonth() + 1).padStart(2, "0");
        const day = String(beginTime.getDate()).padStart(2, "0");
        const hours = String(beginTime.getHours()).padStart(2, "0");
        const minutes = String(beginTime.getMinutes()).padStart(2, "0");
        const seconds = String(beginTime.getSeconds()).padStart(2, "0");
        this.formData.furnaceBegin = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // 更新选择器索引
        this.furnaceBeginPickerIndex = this.dateTimeStringToIndex(
          this.formData.furnaceBegin
        );
      }

      if (recordData.furnaceEnd) {
        // 将后端返回的时间格式转换为前端显示格式
        const endTime = new Date(recordData.furnaceEnd);
        const year = endTime.getFullYear();
        const month = String(endTime.getMonth() + 1).padStart(2, "0");
        const day = String(endTime.getDate()).padStart(2, "0");
        const hours = String(endTime.getHours()).padStart(2, "0");
        const minutes = String(endTime.getMinutes()).padStart(2, "0");
        const seconds = String(endTime.getSeconds()).padStart(2, "0");
        this.formData.furnaceEnd = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // 更新选择器索引
        this.furnaceEndPickerIndex = this.dateTimeStringToIndex(
          this.formData.furnaceEnd
        );
      }

      // 重量信息（格式化保留2位小数）
      this.formData.furnaceTareWg = this.formatWeight(recordData.furnaceTareWg);
      this.formData.furnaceOutWg = this.formatWeight(recordData.furnaceOutWg);
      this.formData.arBlowCost = recordData.arBlowCost || "";

      // 合格和废品信息（格式化保留2位小数）
      this.formData.qaCount = recordData.qaCount || "";
      this.formData.qaWg = this.formatWeight(recordData.qaWg);
      this.formData.scrapCount = recordData.scrapCount || "";
      this.formData.scrapWg = this.formatWeight(recordData.scrapWg);
      this.formData.scrapReason = recordData.scrapReason || "";
      // 是否回炉（从reserveVarchar1读取）
      // 兼容多种可能的字段名和值格式
      const reserveVarchar1Value =
        recordData.reserveVarchar1 || recordData.reserve_varchar1 || "";
      this.formData.isReheat =
        reserveVarchar1Value === "是" ||
        reserveVarchar1Value === "1" ||
        reserveVarchar1Value === true;
      // 如果是从数据库加载的"是"状态，标记为来自数据库，不允许编辑
      this.isReheatFromDB = this.formData.isReheat;
      console.log(
        "是否回炉字段值:",
        reserveVarchar1Value,
        "isReheat:",
        this.formData.isReheat,
        "isReheatFromDB:",
        this.isReheatFromDB
      );
    },

    // 重置表单数据（保留炉次号）
    resetFormDataExceptFurnace() {
      const currentFurnaceNo = this.formData.furnaceNo;
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: this.formData.processCode,
        processName: this.formData.processName,
        furnaceNo: currentFurnaceNo,
        operationMemo: "",
        furnaceBegin: "",
        furnaceEnd: "",
        furnaceTareWg: "",
        furnaceCostWg: "",
        furnaceOutWg: "",
        arBlowCost: "",
        qaCount: "",
        qaWg: "",
        scrapCount: "",
        scrapWg: "",
        scrapReason: "",
        isReheat: false,
      };
      // 重置是否回炉来自数据库的标志
      this.isReheatFromDB = false;
      // 重置选择器索引
      this.furnaceBeginPickerIndex = [0, 0, 0, 0, 0, 0];
      this.furnaceEndPickerIndex = [0, 0, 0, 0, 0, 0];
    },

    // 格式化重量为2位小数
    formatWeight(value) {
      // 如果值为空、null、undefined，返回空字符串
      if (value === null || value === undefined || value === "") {
        return "";
      }
      const num = parseFloat(value);
      if (isNaN(num)) {
        return "";
      }
      // 确保保留2位小数，包括0值也显示为 "0.00"
      return num.toFixed(2);
    },

    // 数字验证
    validateNumber(event, obj, field) {
      const inputValue = event.detail.value;

      // 如果输入为空，清空字段
      if (!inputValue || inputValue.trim() === "") {
        const weightFields = [
          "furnaceTareWg",
          "furnaceOutWg",
          "qaWg",
          "scrapWg",
        ];
        if (weightFields.includes(field)) {
          obj[field] = "";
        } else {
          obj[field] = "";
        }
        return;
      }

      const value = parseFloat(inputValue);
      if (isNaN(value) || value < 0) {
        obj[field] = "";
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
      } else {
        // 重量类字段统一保留2位小数
        const weightFields = [
          "furnaceTareWg",
          "furnaceOutWg",
          "qaWg",
          "scrapWg",
        ];
        if (weightFields.includes(field)) {
          // 强制格式化为2位小数
          obj[field] = this.formatWeight(value);
        } else {
          obj[field] = value;
        }
      }
    },

    // 切换是否回炉状态（点击checkbox或文字都可以切换）
    toggleReheat() {
      this.formData.isReheat = !this.formData.isReheat;
    },

    // 处理是否回炉点击事件（带禁用检查）
    handleReheatClick() {
      // 如果是从数据库加载的"是"状态（已提交的记录），不允许编辑
      if (this.isReheatFromDB) {
        return;
      }
      // 否则允许切换状态（包括选中和取消选中）
      this.toggleReheat();
    },

    // 将日期时间字符串转换为选择器索引
    dateTimeStringToIndex(dateTimeStr) {
      const currentYear = new Date().getFullYear();
      const startYear = currentYear - 10;

      if (!dateTimeStr) {
        const now = new Date();
        return [
          now.getFullYear() - startYear, // 年份索引（相对于起始年份）
          now.getMonth(), // 月份索引（0-11）
          now.getDate() - 1, // 日期索引（0-30）
          now.getHours(), // 小时索引（0-23）
          now.getMinutes(), // 分钟索引（0-59）
          now.getSeconds(), // 秒索引（0-59）
        ];
      }

      try {
        const [datePart, timePart] = dateTimeStr.split(" ");
        const [year, month, day] = datePart.split("-").map(Number);
        const [hours, minutes, seconds] = timePart.split(":").map(Number);

        return [
          year - startYear, // 年份索引
          month - 1, // 月份索引（0-11）
          day - 1, // 日期索引（0-30）
          hours, // 小时索引（0-23）
          minutes, // 分钟索引（0-59）
          seconds, // 秒索引（0-59）
        ];
      } catch (error) {
        console.error("日期时间转换失败:", error);
        const now = new Date();
        return [
          now.getFullYear() - startYear,
          now.getMonth(),
          now.getDate() - 1,
          now.getHours(),
          now.getMinutes(),
          now.getSeconds(),
        ];
      }
    },

    // 将选择器索引转换为日期时间字符串
    indexToDateTimeString(indexes) {
      const [
        yearIndex,
        monthIndex,
        dayIndex,
        hourIndex,
        minuteIndex,
        secondIndex,
      ] = indexes;
      const currentYear = new Date().getFullYear();
      const startYear = currentYear - 10;

      const year = startYear + yearIndex;
      const month = String(monthIndex + 1).padStart(2, "0");
      const day = String(dayIndex + 1).padStart(2, "0");
      const hour = String(hourIndex).padStart(2, "0");
      const minute = String(minuteIndex).padStart(2, "0");
      const second = String(secondIndex).padStart(2, "0");

      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    // 处理炉次开始时间选择变化
    handleFurnaceBeginChange(e) {
      const indexes = e.detail.value;
      this.furnaceBeginPickerIndex = indexes;
      this.formData.furnaceBegin = this.indexToDateTimeString(indexes);
    },

    // 处理炉次结束时间选择变化
    handleFurnaceEndChange(e) {
      const indexes = e.detail.value;
      this.furnaceEndPickerIndex = indexes;
      this.formData.furnaceEnd = this.indexToDateTimeString(indexes);
    },

    // 重置表单
    handleReset() {
      // 重置hasRecordData状态
      this.hasRecordData = false;
      this.currentRecordId = null;
      this.currentBusStatus = null;
      // 重置炉次查询日期为当前日期
      this.furnaceDate = dateHelperApi.getCurrentDate();
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: this.formData.processCode,
        processName: this.formData.processName,
        furnaceNo:
          this.furnaceNoList.length > 0
            ? this.furnaceNoList[this.currentFurnaceIndex]
            : "",
        operationMemo: "",
        furnaceBegin: "",
        furnaceEnd: "",
        furnaceTareWg: "",
        furnaceCostWg: "",
        furnaceOutWg: "",
        arBlowCost: "",
        qaCount: "",
        qaWg: "",
        scrapCount: "",
        scrapWg: "",
        scrapReason: "",
        isReheat: false,
      };
      // 重置是否回炉来自数据库的标志
      this.isReheatFromDB = false;
      // 重置选择器索引
      this.furnaceBeginPickerIndex = [0, 0, 0, 0, 0, 0];
      this.furnaceEndPickerIndex = [0, 0, 0, 0, 0, 0];
      this.currentFurnaceIndex = 0;
      // 重新加载炉次列表
      this.loadFurnaceNoList();
      uni.showToast({
        title: "表单已重置",
        icon: "success",
      });
    },

    // 冶炼开始
    handleStartSmelting() {
      if (this.hasRecordData) {
        uni.showToast({
          title: "该炉次已有数据，不能重复操作",
          icon: "none",
        });
        return;
      }

      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      // 自动填充炉次开始时间为当前时间
      const currentTime = new Date();
      const year = currentTime.getFullYear();
      const month = String(currentTime.getMonth() + 1).padStart(2, "0");
      const day = String(currentTime.getDate()).padStart(2, "0");
      const hours = String(currentTime.getHours()).padStart(2, "0");
      const minutes = String(currentTime.getMinutes()).padStart(2, "0");
      const seconds = String(currentTime.getSeconds()).padStart(2, "0");

      // 使用 yyyy-MM-dd HH:mm:ss 格式
      this.formData.furnaceBegin = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      // 更新选择器索引
      this.furnaceBeginPickerIndex = this.dateTimeStringToIndex(
        this.formData.furnaceBegin
      );

      uni.showLoading({ title: "正在开始冶炼..." });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: "冶炼开始成功",
          icon: "success",
        });
      }, 1500);
    },

    // 冶炼结束
    handleEndSmelting() {
      if (this.hasRecordData) {
        uni.showToast({
          title: "该炉次已有数据，不能重复操作",
          icon: "none",
        });
        return;
      }

      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      // 自动填充炉次结束时间为当前时间
      const currentTime = new Date();
      const year = currentTime.getFullYear();
      const month = String(currentTime.getMonth() + 1).padStart(2, "0");
      const day = String(currentTime.getDate()).padStart(2, "0");
      const hours = String(currentTime.getHours()).padStart(2, "0");
      const minutes = String(currentTime.getMinutes()).padStart(2, "0");
      const seconds = String(currentTime.getSeconds()).padStart(2, "0");

      // 使用 yyyy-MM-dd HH:mm:ss 格式
      this.formData.furnaceEnd = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      // 更新选择器索引
      this.furnaceEndPickerIndex = this.dateTimeStringToIndex(
        this.formData.furnaceEnd
      );

      uni.showLoading({ title: "正在结束冶炼..." });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: "冶炼结束成功",
          icon: "success",
        });
      }, 1500);
    },

    // 打开改号弹窗
    async handleChangeSteelGrade() {
      if (!this.currentRecordNo) {
        uni.showToast({
          title: "未找到记录编号",
          icon: "none",
        });
        return;
      }

      // 加载钢种列表
      await this.loadSteelGradeOptions();

      // 重置选择
      this.selectedSteelGradeIndex = -1;
      this.selectedSteelGrade = null;
      this.showSteelGradeDropdown = false;
      this.steelGradeSearchKeyword = ""; // 重置搜索关键词

      // 显示弹窗
      this.showChangeSteelGradeDialog = true;
    },

    // 加载钢种选项列表
    async loadSteelGradeOptions() {
      try {
        uni.showLoading({ title: "加载中..." });
        const response = await SteelGradeApi.getSimpleList();
        uni.hideLoading();
        console.log("钢种列表API响应:", response);

        // 检查响应格式
        if (!response) {
          console.error("API响应为空");
          this.steelGradeOptions = [];
          uni.showToast({
            title: "API响应为空",
            icon: "none",
          });
          return;
        }

        // 处理不同的响应格式
        let dataList = null;
        if (response.code === 0 || response.code === 200) {
          // 标准格式：{code: 0, data: [...]}
          dataList = response.data;
        } else if (Array.isArray(response)) {
          // 直接返回数组格式
          dataList = response;
        } else if (response.data && Array.isArray(response.data)) {
          // 嵌套data格式
          dataList = response.data;
        }

        if (dataList && Array.isArray(dataList) && dataList.length > 0) {
          // 将钢种数据转换为选项格式：{code, name, label: "编码-名称"}
          this.steelGradeOptions = dataList.map((item) => ({
            code: item.steelGradeCode || item.code || "",
            name: item.steelGradeName || item.name || "",
            label: `${item.steelGradeCode || item.code || ""}-${
              item.steelGradeName || item.name || ""
            }`,
          }));
          console.log("钢种选项列表:", this.steelGradeOptions);
        } else {
          this.steelGradeOptions = [];
          console.warn("钢种列表为空或格式不正确:", response);
          uni.showToast({
            title: "暂无可用钢种数据",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("加载钢种列表失败:", error);
        this.steelGradeOptions = [];
        uni.showToast({
          title: "加载钢种列表失败: " + (error.message || "未知错误"),
          icon: "none",
        });
      }
    },

    // 钢种搜索处理
    handleSteelGradeSearch() {
      // 搜索逻辑在computed属性filteredSteelGradeOptions中处理
      // 这里可以添加其他搜索相关的逻辑
    },

    // 钢种选择器变化（自定义下拉选择）
    selectSteelGradeByItem(item) {
      // 找到原始列表中的索引
      const originalIndex = this.steelGradeOptions.findIndex(
        (opt) => opt.code === item.code
      );
      this.selectedSteelGradeIndex = originalIndex >= 0 ? originalIndex : -1;
      this.selectedSteelGrade = item;
      this.showSteelGradeDropdown = false; // 选择后关闭下拉列表
      this.steelGradeSearchKeyword = ""; // 清空搜索关键词
    },

    // 确认改号
    async handleConfirmChangeSteelGrade() {
      if (!this.selectedSteelGrade) {
        uni.showToast({
          title: "请选择要修改的钢种",
          icon: "none",
        });
        return;
      }

      if (!this.currentRecordNo || !this.formData.furnaceNo) {
        uni.showToast({
          title: "缺少必要信息",
          icon: "none",
        });
        return;
      }

      // 检查是否已出库
      try {
        uni.showLoading({ title: "检查中..." });
        const checkResponse = await SxRecordApi.checkIfOutbound({
          furnaceNo: this.formData.furnaceNo,
          recordNo: this.currentRecordNo,
        });
        uni.hideLoading();

        if (checkResponse.code === 0) {
          if (checkResponse.data === true) {
            // 已出库，不允许改号
            uni.showToast({
              title: "提纯已出库无法改号",
              icon: "none",
              duration: 3000,
            });
            return;
          }

          // 未出库，执行改号
          uni.showLoading({ title: "改号中..." });
          const changeResponse = await SxRecordApi.changeSteelGrade({
            furnaceNo: this.formData.furnaceNo,
            recordNo: this.currentRecordNo,
            oldSteelGradeName: this.currentSteelGradeName,
            newSteelGradeName: this.selectedSteelGrade.name,
            newSteelGradeCode: this.selectedSteelGrade.code,
          });
          uni.hideLoading();

          if (changeResponse.code === 0) {
            uni.showToast({
              title: "改号成功",
              icon: "success",
            });

            // 关闭弹窗
            this.showChangeSteelGradeDialog = false;

            // 更新当前钢种名称
            this.currentSteelGradeName = this.selectedSteelGrade.name;

            // 重新加载记录数据
            await this.checkAndLoadRecordData(this.formData.furnaceNo);
          } else {
            uni.showToast({
              title: changeResponse.msg || "改号失败",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: checkResponse.msg || "检查出库状态失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("改号失败:", error);
        uni.showToast({
          title: "改号失败，请重试",
          icon: "none",
        });
      }
    },

    // 暂存
    async handleSave() {
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      // 提交前确保重量保留2位小数
      ["furnaceTareWg", "furnaceOutWg", "qaWg", "scrapWg"].forEach((k) => {
        const v = parseFloat(this.formData[k]);
        if (!isNaN(v)) this.formData[k] = this.formatWeight(v);
      });

      try {
        uni.showLoading({ title: "正在暂存..." });

        // 构建提交数据
        // 转换时间格式：将 "YYYY-MM-DD HH:mm:ss" 转换为时间戳（毫秒）
        const formatDateTimeForBackend = (dateTimeStr) => {
          if (!dateTimeStr || !dateTimeStr.trim()) {
            return null;
          }

          try {
            // 解析时间字符串 "YYYY-MM-DD HH:mm:ss"
            let timeStr = dateTimeStr.trim();

            // 如果包含空格，替换为T以便解析
            if (timeStr.includes(" ")) {
              timeStr = timeStr.replace(" ", "T");
            }

            // 确保格式完整：YYYY-MM-DDTHH:mm:ss
            if (timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/)) {
              timeStr = timeStr + ":00";
            }

            // 验证格式是否正确
            if (!timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)) {
              console.error("时间格式不正确:", dateTimeStr);
              return null;
            }

            // 解析日期时间组件
            const [datePart, timePart] = timeStr.split("T");
            const [year, month, day] = datePart.split("-").map(Number);
            const [hours, minutes, seconds] = timePart.split(":").map(Number);

            // 创建Date对象（使用本地时区）
            const date = new Date(
              year,
              month - 1,
              day,
              hours,
              minutes,
              seconds || 0
            );

            // 验证日期有效性
            if (isNaN(date.getTime())) {
              console.error("无效的日期时间:", dateTimeStr);
              return null;
            }

            // 返回时间戳（毫秒）
            return date.getTime();
          } catch (error) {
            console.error("时间格式转换失败:", dateTimeStr, error);
            return null;
          }
        };

        const submitData = {
          // 如果有已有记录，需要包含ID用于更新
          id: this.currentRecordId || null,
          // 基本信息
          processNo: this.formData.processCode,
          processName: this.formData.processName,
          furnaceNo: this.formData.furnaceNo,
          recordMemo: this.formData.operationMemo || "",
          workShift: this.workShift || "",
          wortkType: this.workClass || "",

          // 时间信息（转换为后端可接受的格式）
          ywDate: this.formData.currentDate
            ? new Date(this.formData.currentDate + "T00:00:00").getTime()
            : new Date().setHours(0, 0, 0, 0),
          furnaceBegin: formatDateTimeForBackend(this.formData.furnaceBegin),
          furnaceEnd: formatDateTimeForBackend(this.formData.furnaceEnd),

          // 重量信息
          furnaceTareWg: this.formData.furnaceTareWg || null,
          furnaceOutWg: this.formData.furnaceOutWg || null,
          arBlowCost: this.formData.arBlowCost || null,

          // 合格和废品信息
          qaCount: this.formData.qaCount || null,
          qaWg: this.formData.qaWg || null,
          scrapCount: this.formData.scrapCount || null,
          scrapWg: this.formData.scrapWg || null,
          scrapReason: this.formData.scrapReason || "",

          // 是否回炉（写入reserveVarchar1）
          reserveVarchar1: this.formData.isReheat ? "是" : "否",

          // 业务状态（暂存）
          busStatus: "暂存",
        };

        console.log("暂存数据:", submitData);

        // 调用后端暂存方法（只写入实绩表，不写入库存）
        const response = await SxRecordApi.saveSxRecord(submitData);

        uni.hideLoading();

        if (response.code === 0) {
          uni.showToast({
            title: "暂存成功",
            icon: "success",
          });

          // 暂存成功后，重新检查该炉次的数据状态（因为已经保存了数据）
          await this.checkAndLoadRecordData(this.formData.furnaceNo);
        } else {
          uni.showToast({
            title: response.message || "暂存失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("暂存失败:", error);
        uni.showToast({
          title: "暂存失败: " + (error.message || "未知错误"),
          icon: "none",
        });
      }
    },

    // 下线
    async handleOffline() {
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      // 提交前确保重量保留2位小数
      ["furnaceTareWg", "furnaceOutWg", "qaWg", "scrapWg"].forEach((k) => {
        const v = parseFloat(this.formData[k]);
        if (!isNaN(v)) this.formData[k] = this.formatWeight(v);
      });

      if (!this.formData.furnaceBegin) {
        uni.showToast({
          title: "请先点击冶炼开始",
          icon: "none",
        });
        return;
      }

      if (!this.formData.furnaceEnd) {
        uni.showToast({
          title: "请先点击冶炼结束",
          icon: "none",
        });
        return;
      }

      // 验证合格重量：必须有值且不为0
      const qaWgValue = Number(this.formData.qaWg || 0);
      if (!this.formData.qaWg || qaWgValue === 0) {
        uni.showToast({
          title: "合格重量为空不允许下线！",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认下线",
        content: `确定要将炉次号 ${this.formData.furnaceNo} 下线吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: "正在下线..." });

              // 构建提交数据
              // 转换时间格式：将 "YYYY-MM-DD HH:mm:ss" 转换为时间戳（毫秒）
              // 后端配置了 LocalDateTime 使用时间戳格式进行反序列化
              const formatDateTimeForBackend = (dateTimeStr) => {
                if (!dateTimeStr || !dateTimeStr.trim()) {
                  return null;
                }

                try {
                  // 解析时间字符串 "YYYY-MM-DD HH:mm:ss"
                  let timeStr = dateTimeStr.trim();

                  // 如果包含空格，替换为T以便解析
                  if (timeStr.includes(" ")) {
                    timeStr = timeStr.replace(" ", "T");
                  }

                  // 确保格式完整：YYYY-MM-DDTHH:mm:ss
                  if (timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/)) {
                    timeStr = timeStr + ":00";
                  }

                  // 验证格式是否正确
                  if (!timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)) {
                    console.error("时间格式不正确:", dateTimeStr);
                    return null;
                  }

                  // 解析日期时间组件
                  const [datePart, timePart] = timeStr.split("T");
                  const [year, month, day] = datePart.split("-").map(Number);
                  const [hours, minutes, seconds] = timePart
                    .split(":")
                    .map(Number);

                  // 创建Date对象（使用本地时区）
                  const date = new Date(
                    year,
                    month - 1,
                    day,
                    hours,
                    minutes,
                    seconds || 0
                  );

                  // 验证日期有效性
                  if (isNaN(date.getTime())) {
                    console.error("无效的日期时间:", dateTimeStr);
                    return null;
                  }

                  // 返回时间戳（毫秒）
                  return date.getTime();
                } catch (error) {
                  console.error("时间格式转换失败:", dateTimeStr, error);
                  return null;
                }
              };

              const submitData = {
                // 基本信息
                processNo: this.formData.processCode,
                processName: this.formData.processName,
                furnaceNo: this.formData.furnaceNo,
                recordMemo: this.formData.operationMemo || "",
                workShift: this.workShift || "",
                wortkType: this.workClass || "",

                // 时间信息（转换为后端可接受的格式）
                // ywDate 也是 LocalDateTime 类型，需要转换为时间戳
                ywDate: this.formData.currentDate
                  ? new Date(this.formData.currentDate + "T00:00:00").getTime()
                  : new Date().setHours(0, 0, 0, 0),
                furnaceBegin: formatDateTimeForBackend(
                  this.formData.furnaceBegin
                ),
                furnaceEnd: formatDateTimeForBackend(this.formData.furnaceEnd),

                // 重量信息
                furnaceTareWg: this.formData.furnaceTareWg || null,
                furnaceOutWg: this.formData.furnaceOutWg || null,
                arBlowCost: this.formData.arBlowCost || null,

                // 合格和废品信息
                qaCount: this.formData.qaCount || null,
                qaWg: this.formData.qaWg || null,
                scrapCount: this.formData.scrapCount || null,
                scrapWg: this.formData.scrapWg || null,
                scrapReason: this.formData.scrapReason || "",

                // 是否回炉（写入reserveVarchar1）
                reserveVarchar1: this.formData.isReheat ? "是" : "否",

                // 业务状态
                busStatus: "下线",
              };

              console.log("提交数据:", submitData);
              console.log("时间字段详情:", {
                furnaceBegin: this.formData.furnaceBegin,
                formattedFurnaceBegin: formatDateTimeForBackend(
                  this.formData.furnaceBegin
                ),
                furnaceEnd: this.formData.furnaceEnd,
                formattedFurnaceEnd: formatDateTimeForBackend(
                  this.formData.furnaceEnd
                ),
              });

              // 调用后端下线方法（包含写入实绩、入库履历、更新库存）
              const response = await SxRecordApi.offlineSxRecord(submitData);

              uni.hideLoading();

              if (response.code === 0) {
                uni.showToast({
                  title: "下线成功",
                  icon: "success",
                });

                // 下线成功后，重新检查该炉次的数据状态（因为已经保存了数据）
                await this.checkAndLoadRecordData(this.formData.furnaceNo);
              } else {
                uni.showToast({
                  title: response.message || "下线失败",
                  icon: "none",
                });
              }
            } catch (error) {
              uni.hideLoading();
              console.error("下线失败:", error);
              uni.showToast({
                title: "下线失败: " + (error.message || "未知错误"),
                icon: "none",
              });
            }
          }
        },
      });
    },

    // 修改记录
    async handleUpdate() {
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先选择炉次号",
          icon: "none",
        });
        return;
      }

      if (!this.currentRecordId) {
        uni.showToast({
          title: "记录ID不存在，无法修改",
          icon: "none",
        });
        return;
      }

      // 提交前确保重量保留2位小数
      ["furnaceTareWg", "furnaceOutWg", "qaWg", "scrapWg"].forEach((k) => {
        const v = parseFloat(this.formData[k]);
        if (!isNaN(v)) this.formData[k] = this.formatWeight(v);
      });
      if (!this.formData.furnaceBegin) {
        uni.showToast({
          title: "请填写炉次开始时间",
          icon: "none",
        });
        return;
      }

      if (!this.formData.furnaceEnd) {
        uni.showToast({
          title: "请填写炉次结束时间",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认修改",
        content: `确定要修改炉次号 ${this.formData.furnaceNo} 的数据吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: "正在修改..." });

              // 构建提交数据
              // 转换时间格式：将 "YYYY-MM-DD HH:mm:ss" 转换为时间戳（毫秒）
              // 后端配置了 LocalDateTime 使用时间戳格式进行反序列化
              const formatDateTimeForBackend = (dateTimeStr) => {
                if (!dateTimeStr || !dateTimeStr.trim()) {
                  return null;
                }

                try {
                  // 解析时间字符串 "YYYY-MM-DD HH:mm:ss"
                  let timeStr = dateTimeStr.trim();

                  // 如果包含空格，替换为T以便解析
                  if (timeStr.includes(" ")) {
                    timeStr = timeStr.replace(" ", "T");
                  }

                  // 确保格式完整：YYYY-MM-DDTHH:mm:ss
                  if (timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/)) {
                    timeStr = timeStr + ":00";
                  }

                  // 验证格式是否正确
                  if (!timeStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)) {
                    console.error("时间格式不正确:", dateTimeStr);
                    return null;
                  }

                  // 解析日期时间组件
                  const [datePart, timePart] = timeStr.split("T");
                  const [year, month, day] = datePart.split("-").map(Number);
                  const [hours, minutes, seconds] = timePart
                    .split(":")
                    .map(Number);

                  // 创建Date对象（使用本地时区）
                  const date = new Date(
                    year,
                    month - 1,
                    day,
                    hours,
                    minutes,
                    seconds || 0
                  );

                  // 验证日期有效性
                  if (isNaN(date.getTime())) {
                    console.error("无效的日期时间:", dateTimeStr);
                    return null;
                  }

                  // 返回时间戳（毫秒）
                  return date.getTime();
                } catch (error) {
                  console.error("时间格式转换失败:", dateTimeStr, error);
                  return null;
                }
              };

              const submitData = {
                // 必须包含ID用于更新
                id: this.currentRecordId,
                // 基本信息
                processNo: this.formData.processCode,
                processName: this.formData.processName,
                furnaceNo: this.formData.furnaceNo,
                recordMemo: this.formData.operationMemo || "",
                workShift: this.workShift || "",
                wortkType: this.workClass || "",

                // 时间信息（转换为后端可接受的格式）
                // ywDate 也是 LocalDateTime 类型，需要转换为时间戳
                ywDate: this.formData.currentDate
                  ? new Date(this.formData.currentDate + "T00:00:00").getTime()
                  : new Date().setHours(0, 0, 0, 0),
                furnaceBegin: formatDateTimeForBackend(
                  this.formData.furnaceBegin
                ),
                furnaceEnd: formatDateTimeForBackend(this.formData.furnaceEnd),

                // 重量信息
                furnaceTareWg: this.formData.furnaceTareWg || null,
                furnaceOutWg: this.formData.furnaceOutWg || null,
                arBlowCost: this.formData.arBlowCost || null,

                // 合格和废品信息
                qaCount: this.formData.qaCount || null,
                qaWg: this.formData.qaWg || null,
                scrapCount: this.formData.scrapCount || null,
                scrapWg: this.formData.scrapWg || null,
                scrapReason: this.formData.scrapReason || "",

                // 是否回炉（写入reserveVarchar1）
                reserveVarchar1: this.formData.isReheat ? "是" : "否",

                // 业务状态
                busStatus: "下线",
              };

              console.log("修改数据:", submitData);
              console.log("时间字段详情:", {
                furnaceBegin: this.formData.furnaceBegin,
                formattedFurnaceBegin: formatDateTimeForBackend(
                  this.formData.furnaceBegin
                ),
                furnaceEnd: this.formData.furnaceEnd,
                formattedFurnaceEnd: formatDateTimeForBackend(
                  this.formData.furnaceEnd
                ),
              });

              // 调用后端更新方法
              const response = await SxRecordApi.updateSxRecord(submitData);

              uni.hideLoading();

              if (response.code === 0) {
                uni.showToast({
                  title: "修改成功",
                  icon: "success",
                });

                // 修改成功后，重新检查该炉次的数据状态（刷新数据）
                await this.checkAndLoadRecordData(this.formData.furnaceNo);
              } else {
                uni.showToast({
                  title: response.message || "修改失败",
                  icon: "none",
                });
              }
            } catch (error) {
              uni.hideLoading();
              console.error("修改失败:", error);
              uni.showToast({
                title: "修改失败: " + (error.message || "未知错误"),
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";

// 按钮禁用样式
.btn-disabled {
  opacity: 0.5;
  background-color: #ccc !important;
  color: #999 !important;
  cursor: not-allowed;
}

// 改号弹窗样式
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 10vh;
  z-index: 9999;
}

.dialog-content {
  background-color: #fff;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  overflow: visible;
  position: relative;
  z-index: 10000;
  max-height: 50vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  transform: translateZ(0);
}

.dialog-header {
  padding: 30rpx;
  border-bottom: 1px solid #e0e0e0;
  text-align: center;
}

.dialog-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.dialog-body {
  padding: 30rpx;
  overflow: visible;
  position: relative;
  z-index: auto;
}

.dialog-row {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.dialog-label {
  font-size: 28rpx;
  color: #666;
  min-width: 200rpx;
  margin-right: 20rpx;
}

.dialog-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.dialog-picker-wrapper {
  flex: 1;
  position: relative;
  z-index: 10001;
}

.dialog-picker {
  flex: 1;
  position: relative;
  z-index: 1;
}

.picker-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fafafa;
  position: relative;
  z-index: 1;
  cursor: pointer;
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
  transition: transform 0.3s;

  &.arrow-up {
    transform: rotate(180deg);
  }
}

// 自定义下拉列表样式
.custom-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4rpx;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  z-index: 10002;
  max-height: 600rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dropdown-search {
  padding: 20rpx;
  border-bottom: 1px solid #e0e0e0;
  background-color: #fafafa;
}

.search-input {
  width: 100%;
  padding: 24rpx 20rpx;
  border: 1px solid #e0e0e0;
  border-radius: 6rpx;
  background-color: #fff;
  font-size: 32rpx;
  box-sizing: border-box;
  min-height: 80rpx;
  line-height: 1.5;
}

.dropdown-scroll {
  flex: 1;
  max-height: 500rpx;
  overflow-y: auto;
}

.dropdown-item {
  padding: 24rpx 20rpx;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f5f5f5;
  }

  &.dropdown-item-selected {
    background-color: #e3f2fd;
    color: #007aff;
  }

  text {
    font-size: 28rpx;
    color: #333;
  }

  &.dropdown-item-selected text {
    color: #007aff;
    font-weight: 600;
  }
}

.dropdown-empty {
  padding: 40rpx 20rpx;
  text-align: center;

  text {
    font-size: 28rpx;
    color: #999;
  }
}

.dialog-footer {
  display: flex;
  border-top: 1px solid #e0e0e0;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  padding: 30rpx;
  text-align: center;
  font-size: 32rpx;
  border: none;
  background-color: transparent;
}

.btn-cancel {
  color: #666;
  border-right: 1px solid #e0e0e0;
}

.btn-confirm {
  color: #007aff;
  font-weight: 600;
}

// 自定义checkbox样式
.custom-checkbox-wrapper {
  cursor: pointer;
  user-select: none;
  -webkit-tap-highlight-color: transparent;

  &.checkbox-disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.custom-checkbox-icon {
  &.checkbox-checked {
    background-color: #007aff !important;
    border-color: #007aff !important;
  }

  &.checkbox-disabled {
    background-color: #e0e0e0 !important;
    border-color: #ccc !important;
    cursor: not-allowed;
  }

  &:active:not(.checkbox-disabled) {
    transform: scale(0.95);
  }
}

// 作业数据区字体增强（仅此页）
.plan-form-container .form-section .form-label {
  font-size: 16px; // 原基础上增大
  font-weight: 600;
}
.plan-form-container .form-section .form-input,
.plan-form-container .form-section .picker-content {
  font-size: 16px;
}
.plan-form-container .section-title {
  font-size: 18px;
}

// 去掉生产工序、炉次输入、炉次开始时间、炉次结束时间控件的外部边框
// .plan-form-container .form-section .form-picker {
//   border: none !important;
//   background: transparent !important;
//   padding: 20rpx !important;
//   cursor: pointer;
// }

// 按钮组样式（暂存和下线按钮放在一行）
.button-group {
  display: flex;
  gap: 20rpx;
  flex: 1;

  .btn-submit {
    flex: 1;
    min-width: 0; // 允许按钮缩小

    // 如果只有一个按钮，占满整个空间
    &:only-child {
      flex: 1;
    }
  }
}
</style>
